package com.rent.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rent.common.entity.ResponseResult;
import com.rent.common.exception.BusinessException;
import com.rent.common.interceptor.UserContext;
import com.rent.user.pojo.dto.*;
import com.rent.user.pojo.entity.User;
import com.rent.user.pojo.vo.UserBaseInfoVo;
import com.rent.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import java.util.List;
import java.util.Map;

@Api(tags = "用户管理")
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 一键登录（短信验证码登录）
     * POST /api/user/sms-login
     */
    @ApiOperation(value = "一键登录", notes = "使用手机号和短信验证码登录")
    @PostMapping("/sms-login")
    public ResponseResult<Map<String, Object>> smsLogin(
            @ApiParam(value = "一键登录信息", required = true)
            @Validated @RequestBody SmsLoginDto smsLoginDto) {
        Map<String, Object> result = userService.smsLogin(smsLoginDto);
        return ResponseResult.success("登录成功", result);
    }

    /**
     * 发送短信验证码
     * POST /api/user/send-sms-code
     */
    @ApiOperation(value = "发送短信验证码", notes = "发送一键登录的短信验证码")
    @PostMapping("/send-sms-code")
    public ResponseResult<String> sendSmsCode(
            @ApiParam(value = "手机号", required = true)
            @RequestBody @Validated SendSmsCodeDto sendSmsCodeDto) {
        boolean success = userService.sendSmsCode(sendSmsCodeDto.getPhone());
        return success ? ResponseResult.success("验证码发送成功") : ResponseResult.fail("验证码发送失败");
    }

    /**
     * 用户注册
     * POST /api/user/register
     */
    @ApiOperation(value = "用户注册", notes = "新用户注册接口，无需Token")
    @PostMapping("/register")
    public ResponseResult<String> register(
            @ApiParam(value = "注册信息", required = true)
            @Validated @RequestBody RegisterDto registerDto) {
        // 调用userService.register(registerDTO)实现注册逻辑
        userService.register(registerDto);
        return ResponseResult.success("注册成功！");
    }

    /**
     * 用户登录
     * POST /api/user/login
     */
    @ApiOperation(value = "用户登录", notes = "用户登录接口，返回Token")
    @PostMapping("/login")
    public ResponseResult<Map<String, Object>> login(
            @ApiParam(value = "登录信息", required = true)
            @Validated @RequestBody LoginDto loginDto) {
        Map<String, Object> result = userService.login(loginDto);

        return ResponseResult.success("登陆成功!", result);
    }

    /**
     * 获取当前用户信息
     * GET /api/user/info
     */
    @ApiOperation(value = "获取当前用户信息", notes = "根据token获取当前登录用户的详细信息")
    @GetMapping("/info")
    public ResponseResult<User> getUserInfo() {
        Long id = UserContext.getUserId();
        User userInfo = userService.getById(id);
        return ResponseResult.success("获取用户信息成功", userInfo);
    }

    /**
     * 上传头像
     * POST /api/user/uploadHead
     */
    @ApiOperation(value = "上传头像", notes = "上传用户头像图片")
    @PostMapping("/uploadHead")
    public ResponseResult<String> uploadHead(
            @ApiParam(value = "头像文件", required = true)
            @RequestParam MultipartFile file) {
        try {
            String avatarUrl = userService.uploadAvatar(file);
            return ResponseResult.success("上传成功", avatarUrl);
        } catch (Exception e) {
            return ResponseResult.fail("上传失败: " + e.getMessage());
        }
    }

    /**
     * 更新用户信息
     * PUT /api/user/update
     */
    @ApiOperation(value = "更新用户信息", notes = "更新当前登录用户的信息")
    @PostMapping("/update")
    public ResponseResult<?> updateUser(@RequestBody User user) {
        if (userService.updateUser(user)) {
            ResponseResult.success();
        }
        throw new BusinessException("更新用户信息失败");
    }

    /**
     * 获取用户列表
     * GET /api/user/list
     */
    @ApiModelProperty(value = "用户列表", notes = "获取用户列表")
    @GetMapping("/list")
    public ResponseResult<Page<User>> list(UserQueryDto userQueryDto) {
        // 获取分页对象
        Page<User> page = new Page<>(userQueryDto.getPage(), userQueryDto.getLimit());

        // 创建查询条件
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(User::getUsername, userQueryDto.getUsername())
                .eq(User::getRole, userQueryDto.getRole());

        // 执行分页查询
        Page<User> userPage = userService.page(page);

        return ResponseResult.success("获取用户列表成功", userPage);
    }

    /**
     * 删除用户
     * @param id
     * @return Boolean
     */
    @ApiModelProperty(value = "删除用户", notes = "删除用户所有信息")
    @PostMapping("/delete/{id}")
    public ResponseResult<Boolean> delete(@PathVariable Long id) {
        return ResponseResult.success("删除用户成功", userService.removeById(id));
    }

    /**
     * 批量删除用户
     * @param ids
     * @return
     */
    @ApiModelProperty(value = "批量删除用户", notes = "批量删除用户所有信息")
    @PostMapping("/batchRemove")
    public ResponseResult<Boolean> batchRemove(@RequestBody List<Long> ids) {
        return ResponseResult.success("批量删除用户成功", userService.removeByIds(ids));
    }

    /**
     * 分配角色
     * @param updateUserRoleDto
     * @return
     */
    @ApiModelProperty(value = "分配角色", notes = "分配用户角色")
    @PostMapping(value = "/updateUserRole")
    public ResponseResult<?> updateUserRole(@RequestBody UpdateUserRoleDto updateUserRoleDto){
        if (userService.updateUserRole(updateUserRoleDto.getUserId(), updateUserRoleDto.getRoleId())) {
            return ResponseResult.success();
        }
        throw new BusinessException("分配角色失败");
    }

    /**
     * 修改密码
     * @param updatePasswordDto
     * @return
     */
    @ApiModelProperty(value = "修改密码")
    @PostMapping(value = "/updatePassword")
    public ResponseResult<String> updatePassword(
            @ApiParam(value = "修改密码信息", required = true)
            @Validated @RequestBody UpdatePasswordDto updatePasswordDto) {
        userService.updatePassword(updatePasswordDto);
        return ResponseResult.success();
    }

    /**
     * 获取用户统计信息
     * GET /api/user/baseInfoCount
     */
    @ApiOperation(value = "获取用户统计信息", notes = "获取当前用户的各项统计数据")
    @GetMapping("/baseInfoCount")
    public ResponseResult<UserBaseInfoVo> getBaseInfoCount() {
        Long userId = UserContext.getUserId();
        // 验证用户是否登录
        if (userId == null) {
            throw new BusinessException("用户未登录，请先登录");
        }
        UserBaseInfoVo baseInfo = userService.getBaseInfo(userId);
        return ResponseResult.success("查询成功", baseInfo);
    }
}
